package com.imageprocess.demo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.Log;
import android.view.KeyEvent;

import com.imageprocess.R;
import com.imageprocess.ui.ImageZoomView;

/**
 * 这货实现的是水波纹效果
 * 
 * @author dino
 * 
 */
public class WaterView extends ImageZoomView implements Runnable {

	private int width;
	private int height;

	short[] buffer1;
	short[] buffer2;

	int[] Bitmap1;
	int[] Bitmap2;

	public WaterView(Context context) {
		super(context);
		Bitmap bitmap = (BitmapFactory.decodeResource(this.getResources(),
				R.drawable.demoimg));
		this.setImage(bitmap);
		width = getImage().getWidth();
		height = getImage().getHeight();
		Log.d("WaterView", "width:"+width);
		Log.d("WaterView", "height:"+height);
		buffer1 = new short[width * height];
		buffer2 = new short[width * height];

		Bitmap1 = new int[width * height];
		Bitmap2 = new int[width * height];

		getImage().getPixels(Bitmap1, 0, width, 0, 0, width, height);
		new Thread(this).start();
	}

	void DropStone(int x, int y, int stonesize, int stoneweight) {
		for (int posx = x - stonesize; posx < x + stonesize; posx++) {
			for (int posy = y - stonesize; posy < y + stonesize; posy++) {
				if ((posx - x) * (posx - x) + (posy - y) * (posy - y) < stonesize
						* stonesize) {
					buffer1[width * posy + posx] = (short) -stoneweight;
				}
			}
		}
	}

	void RippleSpread() {
		for (int i = width; i < width * height - width; i++) {
			buffer2[i] = (short) (((buffer1[i - 1] + buffer1[i + 1]
					+ buffer1[i - width] + buffer1[i + width]) >> 1) - buffer2[i]);
			buffer2[i] -= buffer2[i] >> 5;
		}
		short[] ptmp = buffer1;
		buffer1 = buffer2;
		buffer2 = ptmp;
	}

	void render() {
		int xoff, yoff;
		int k = width;
		for (int i = 1; i < height-1; i++) {
			for (int j = 0; j < width; j++) {
				xoff = buffer1[k - 1] - buffer1[k + 1];
				yoff = buffer1[k - width] - buffer1[k + width];
				if ((i + yoff) < 0) {
					k++;
					continue;
				}
				if ((i + yoff) > height) {
					k++;
					continue;
				}
				if ((j + xoff) < 0) {
					k++;
					continue;

				}
				if ((j + xoff) > width) {
					k++;
					continue;
				}
				int pos1, pos2;
				pos1 = width * (i + yoff) + (j + xoff);
				pos2 = width * i + j;
				Bitmap2[pos2++] = Bitmap1[pos1++];
				k++;
			}
		}
	}
	
	public void onDraw(Canvas canvas){
		super.onDraw(canvas);
		canvas.drawBitmap(Bitmap2, 0,width,0,0,width,height, false,null);
		
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event)
	{
		DropStone(80 ,80, 10, 30);
		return false;
	}

	@Override
	public void run() {
		while(!Thread.currentThread().interrupted()){
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			RippleSpread();
			render();
			postInvalidate();
		}
	}
}
